package com.lightsaber.trade.as.service.device;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lightsaber.trade.as.dao.device.CommandPublishToDeviceDao;
import com.lightsaber.trade.as.dao.device.DeviceDao;
import com.lightsaber.trade.as.entity.device.CommandPublishToDevice;
import com.lightsaber.trade.as.entity.device.Device;
import com.lightsaber.trade.as.ws.api.device.InfoCollectForDeviceDto;
import com.lightsaber.trade.core.dao.BaseDao;
import com.lightsaber.trade.core.service.BaseServiceImpl;

@Service
@Transactional
public class CommandPublishToDeviceManager extends
        BaseServiceImpl<CommandPublishToDevice, String> {

    @Autowired
    CommandPublishToDeviceDao dommandPublishToDeviceDao;

    @Autowired
    DeviceDao deviceDao;

    @Override
    protected BaseDao<CommandPublishToDevice, String> getDao() {
        return dommandPublishToDeviceDao;
    }

    public void save(String deviceId, String content) {
        Device device = deviceDao.get(deviceId);

        CommandPublishToDevice commandPublishToDevice = new CommandPublishToDevice();
        commandPublishToDevice.setContent(content);
        commandPublishToDevice.setDevice(device);
        commandPublishToDevice.setStatus("NoRead");

        this.save(commandPublishToDevice);

    }

    public InfoCollectForDeviceDto generateDtoFromNoReadCommands(String deviceSerialNumber) {
        Device device = deviceDao.findUniqueBy("serialNumber", deviceSerialNumber);
        List<CommandPublishToDevice> noReadCommands = dommandPublishToDeviceDao
                .findNoReadInfo(device);

        List<InfoCollectForDeviceDto.InfoCollectForDevice> infoCollectForDeviceList = new ArrayList<InfoCollectForDeviceDto.InfoCollectForDevice>();

        for (CommandPublishToDevice commandPublishToDevice : noReadCommands) {

            infoCollectForDeviceList.add(new InfoCollectForDeviceDto.InfoCollectForDevice(
                    commandPublishToDevice.getContent(), commandPublishToDevice.getCreatedBy()));

            commandPublishToDevice.setStatus("Read");
            dommandPublishToDeviceDao.save(commandPublishToDevice);
        }

        InfoCollectForDeviceDto infoCollectForDeviceDto = new InfoCollectForDeviceDto();
        infoCollectForDeviceDto.setInfoCollectForDeviceList(infoCollectForDeviceList);
        return infoCollectForDeviceDto;
    }
}
